using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using MvcSoftDemo.Db;
using MvcSoftDemo.Models;

namespace MvcSoftDemo.Repository
{
    public class EfRepository<T> : IRepository<T> where T : Base
    {
        private readonly DemoDb _db;
        private readonly DbSet<T> _table;
        public EfRepository()
        {
            _db = new DemoDb();
            _table = _db.Set<T>();
        }
        public IQueryable<T> Select
        {
            get
            {
                return _table as IQueryable<T>;
            }
        }

        public T GetById(int id)
        {
            var Products = _table.Where(x => x.Id == id).FirstOrDefault();
            return Products;
        }

        public void Insert(T entity)
        {
            if (entity == null)
            {
                throw new System.Exception();
            }

            entity.IsActived = true;
            entity.IsDeleted = false;
            entity.CreateTime = DateTime.Now;
            entity.UpdatedTime = DateTime.Now;
            entity.DisplayOrder = 0;
            entity.Creator = 0;

            _table.Add(entity);
            _db.SaveChanges();
        }

        public void Update(T entity)
        {
            if(entity==null){
                throw new System.Exception();
            }

            entity.UpdatedTime = DateTime.Now;

            _table.Update(entity);
            _db.SaveChanges();
        }
        public void Delete(int id)
        {
            var Products = GetById(id);
            if(Products==null){
                throw new System.Exception();
            }

            Products.IsDeleted = true;

            Update(Products);
        }
    }
}